package com.music.note_android.utils

import android.graphics.Bitmap
import android.util.LruCache

class ThumbnailCache {
    
    private val memoryCache: LruCache<String, Bitmap>
    
    init {
        // 获取可用内存的1/8作为缓存大小
        val maxMemory = (Runtime.getRuntime().maxMemory() / 1024).toInt()
        val cacheSize = maxMemory / 8
        
        memoryCache = object : LruCache<String, Bitmap>(cacheSize) {
            override fun sizeOf(key: String, bitmap: Bitmap): Int {
                // 返回位图的大小（KB）
                return bitmap.byteCount / 1024
            }
            
            override fun entryRemoved(
                evicted: Boolean,
                key: String,
                oldValue: Bitmap,
                newValue: Bitmap?
            ) {
                // 当缓存项被移除时，回收位图
                if (evicted && !oldValue.isRecycled) {
                    oldValue.recycle()
                }
            }
        }
    }
    
    /**
     * 添加位图到缓存
     */
    fun addBitmapToCache(key: String, bitmap: Bitmap) {
        if (getBitmapFromCache(key) == null) {
            memoryCache.put(key, bitmap)
        }
    }
    
    /**
     * 从缓存获取位图
     */
    fun getBitmapFromCache(key: String): Bitmap? {
        return memoryCache.get(key)
    }
    
    /**
     * 从缓存移除位图
     */
    fun removeBitmapFromCache(key: String) {
        val bitmap = memoryCache.remove(key)
        bitmap?.let {
            if (!it.isRecycled) {
                it.recycle()
            }
        }
    }
    
    /**
     * 清空缓存
     */
    fun clearCache() {
        memoryCache.evictAll()
    }
    
    /**
     * 获取缓存大小
     */
    fun getCacheSize(): Int {
        return memoryCache.size()
    }
    
    /**
     * 获取最大缓存大小
     */
    fun getMaxCacheSize(): Int {
        return memoryCache.maxSize()
    }
    
    companion object {
        @Volatile
        private var INSTANCE: ThumbnailCache? = null
        
        fun getInstance(): ThumbnailCache {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: ThumbnailCache().also { INSTANCE = it }
            }
        }
    }
}